package servlet;

import bean.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/userselectlimit")
public class UserSelectLimitServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public UserSelectLimitServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Integer page = 1;
        try {
            page = Integer.parseInt(request.getParameter("p"));
        } catch (Exception e) {
            // handle exception
        }

        Integer pageSize = 7;
        try {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        } catch (Exception e) {
            // handle exception
        }

        // Get the userlist from session
        List<User> userlist = (List<User>) request.getSession().getAttribute("userlist");
        if (userlist == null) {
            userlist = new ArrayList<>(); // Default to an empty list if not found
        }

        Integer total = userlist.size();
        System.out.println("total: " + total);
        Integer tp = total / pageSize;
        if (total % pageSize != 0) tp++;

        Integer start = (page - 1) * pageSize;
        Integer end = Math.min(start + pageSize, total);

        List<User> paginatedUserList = userlist.subList(start, end);

        StringBuilder sb = new StringBuilder();

        if (page > 1) {
            sb.append("<a href=\"../userselectlimit?p=1\">首页</a>&nbsp;&nbsp;");
            sb.append("<a href=\"../userselectlimit?p=").append(page - 1).append("\">上一页</a>&nbsp;&nbsp;");
        }

        for (int i = 1; i <= tp; i++) {
            if (i == page) {
                sb.append("<b>").append(i).append("</b>&nbsp;&nbsp;");
            } else {
                sb.append("<a href=\"../userselectlimit?p=").append(i).append("\">").append(i).append("</a>&nbsp;&nbsp;");
            }
        }

        if (page < tp) {
            sb.append("<a href=\"../userselectlimit?p=").append(page + 1).append("\">下一页</a>&nbsp;&nbsp;");
            sb.append("<a href=\"../userselectlimit?p=").append(tp).append("\">尾页</a>&nbsp;&nbsp;");
        }

        request.getSession().setAttribute("pageUser", sb.toString());
        request.getSession().setAttribute("userselectlist", paginatedUserList);
        request.getSession().setAttribute("startuser", start);

        response.sendRedirect("./jsp/UserMan.jsp"); // Redirect to user management page
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
